﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Subsidiary.CouponWrapper
{
   public class DangDangCouponWrapper:ICouponWrapper
    {
        public static readonly string trPattern = @"<tr.*?class=""table_titlebjk"">(.*?)</tr>";
        public static readonly string tdNumberPattern = @"<td class=""table_titlebj1"" title=""(.+?)"">.*?</td>";
        public static readonly string tdNamePattern = @"<span>(.+?)</span>";
        public static readonly string tdEnPattern = @"<td>可用</td>";
        public static readonly string tdAcmountPattern = @"<td>￥(\d+\.\d{2})";
        public static readonly string tdEndPattern = @"<td class=""table_titlebj6"">(.+?)</td>";
        public static readonly string tdLimitPattern = @"<span class=""aline"">(.*?)</span>";
        public List<CouponItem> PickUp(string html)
        {
            List<CouponItem> coupons = new List<CouponItem>();
            Match trMatch = Regex.Match(html, trPattern);
            while (trMatch != null && trMatch.Success)
            {
                string trHtml = trMatch.Groups[1].Value;
                Match enMatch = Regex.Match(trHtml, tdEnPattern);
                if (enMatch.Success)
                {
                    Match nameMatch = Regex.Match(trHtml, tdNamePattern);
                    Match amountMatch = Regex.Match(trHtml, tdAcmountPattern);
                    Match endMatch = Regex.Match(trHtml, tdEndPattern);
                    Match limitMatch = Regex.Match(trHtml, tdLimitPattern);
                    Match numberMatch = Regex.Match(trHtml, tdNumberPattern);
                    //Match nameMatch = Regex.Match(trHtml, tdNamePattern);
                    CouponItem coupon = new CouponItem
                    {
                        Title = nameMatch.Groups[1].Value,
                        Shop = "当当",
                        Link = "http://www.dwz.cn/4Pr88",
                        EndDate = endMatch.Groups[1].Value,
                        Number = numberMatch.Groups[1].Value,
                        Password = string.Empty,
                        Amount = float.Parse(amountMatch.Groups[1].Value),
                        Comment = limitMatch.Groups[1].Value
                    };
                    coupons.Add(coupon);
                }
                trMatch = trMatch.NextMatch();
            }
            return coupons;
        }
    }
}
